;(function($){
	/***
	 * 资源管理器 
	 */
	$.widget("tempo.explorer", {
		options: {
			title: 'Explorer',
			showTitle: true,
			url: 'local',
			method: 'POST',
			contentType: 'application/x-www-form-urlencoded',
			menus: [],
			data: [],
			selfId: 'self',
			otherId: 'share',
			onBeforeQuery: function(v) {return v; },
			onBeforeLoad: function(v) {return v; },
			onAfterLoad: function(v) {return v; },
			onBeforeLoadChildren: function(v) { return true;},
			onMenuClick: $.noop,
			onItemClick: $.noop,
			onDragEvent:$.noop,
			canDrag:false,
			markIcon:'ui-icon tempo-ui-icon tempo-ui-icon-setting'
		},
		_create: function() {
			this.element.addClass("tempo-explorer");
			this._super();
			this._render();
			this.resize();
			this.loadData();
			this._initMenu();
		},
		_render: function() {
			this._addTitle();
			this._addSearchBox();
			this._addTree();
		},
		_addTitle: function() {
			var title = $('<div/>').addClass('explorer-title').text(this.options.title);
			title.appendTo(this.element);
			if(!!!this.options.showTitle) {
				title.hide();
			}
		},
		_addSearchBox: function() {
			var search = $('<div/>').addClass('explorer-searchbox').appendTo(this.element);
			var $this = this;
			var onSearch = this._search;
			search.searchbar({
				isEnter:true,
				onSearch: function(value) {
					onSearch.call($this, value);
				}
			});
		},
		_addTree: function() {
			var conDiv = $('<div/>').addClass('explorer-condiv').appendTo(this.element)
			var board = $('<div/>').addClass('explorer-treeboard').appendTo(conDiv);
			$('<div/>').addClass('explorer-tree').appendTo(board);
		},
		resize: function() {
			var height = this.element.innerHeight();
			var titleHeight = this.element.find('.explorer-title').outerHeight(true);
			var searchHeight = this.element.find('.explorer-searchbox').outerHeight(true);
			this.element.find('.explorer-treeboard').height(height - titleHeight - searchHeight);
		},
		_search: function(value) {
			var $this = this;
			var param = this.options.param || {};
			param.name = value;
			this.options.param = param;
			if(this.options.url == 'local') {
				//同步模式
				this.element.find('.tempo-groupmenu-content').hide();
				if(!!value) {
					this.element.find('.tempo-groupmenu-title').hide();
				} else {
					this.element.find('.tempo-groupmenu-title').show();
				}
				this.element.find('.tempo-groupmenu-item').hide();
				var itemEles = this.element.find('.explorer-tree').find('.tempo-groupmenu-item').filter(function(index) {
				  return $(this).attr('menuid') != 'undefined';
				});
				if(itemEles && itemEles.size() > 0){
					for (var i = 0; i < itemEles.size(); i++) {
						var itemEle = itemEles.get(i);
						var data = $(itemEle).data('data')
						if(value && value.trim().length > 0){
							if(data.name && data.name.toLowerCase().indexOf(value.toLowerCase()) > -1){
//								if(data.fileType.toLowerCase()=="folder"){
//									continue;
//								}
								if(!data.parentId||data.parentId=="-1"||data.parentId==""){
									$(itemEle).show().parent().show().prev('.tempo-groupmenu-title').show();
								}else{
									var index = $(itemEle).parent().attr("index");
									if(index == 2){
										$(itemEle).show().parent().show().prev('.tempo-groupmenu-item').show().parent().show().prev('.tempo-groupmenu-title').show();
									}else if(index == 3){
										$(itemEle).show().parent().show().prev('.tempo-groupmenu-item').show().parent().show().prev('.tempo-groupmenu-item').show().parent().show().prev('.tempo-groupmenu-title').show();
									}else if(index >= 4){
										$(itemEle).show().parent().show().prev('.tempo-groupmenu-item').show().parent().show().prev('.tempo-groupmenu-item').show().parent().show().prev('.tempo-groupmenu-item').show().parent().show().prev('.tempo-groupmenu-title').show();
									}
								}
							}
						}else{
							//display all
							$(itemEle).show().parent().show().prev('.tempo-groupmenu-item').show().parent().show().prev('.tempo-groupmenu-item').show().parent().show().prev('.tempo-groupmenu-item').show().parent().show().prev('.tempo-groupmenu-title').show();
						}
					}
				}
			}else{
				$.ajax({
					url: this.options.url,
					method: 'POST',
					contentType: 'application/json;charset=utf8',
					data:  JSON.stringify({"name":value}),
					success: function(data) {
						var beforeQuery = $this.options.onBeforeQuery;
						var afterLoad = $this.options.onAfterLoad;
						var data = afterLoad.call($this, data, false);
						data = $this._dataProcess(data);
						$this._showTree(data, false);
					}
				})
			}
		},
		loadData: function(data) { 
			var $this = this;
			var beforeLoad = this.options.onBeforeLoad;
			var _data = this._dataProcess(data || this.options.data);
			if(this.options.url == 'local') {
				$this._showTree(_data, false);
			} else {  
				var beforeQuery = this.options.onBeforeQuery;
				var afterLoad = this.options.onAfterLoad;
				var param = $.extend({}, this.options.param);
				param = beforeQuery.call($this, param);
				$this._ajax(param || {}, function(d) {
					var data = afterLoad.call($this, d, false);
					data = $this._dataProcess(data);
					$this._showTree(data, false);
				});           
			}
		}, 
		_dataProcess: function(data) {
			if($.isArray(data)) {
				for(var i in data) {
					this._dataProcess(data[i]);
				}
			} else {
				data.title = data.name;
				data.icon = 'ui-icon tempo-ui-icon tempo-ui-icon-no-mutual ';
				if(data.fileType == 'FILE') {
					data.icon += 'tempo-ui-icon-scene';
				} else if(data.fileType == 'FOLDER') {
					data.icon += 'tempo-ui-icon-tree-dir-close';
					data.groupType = 'folder';
					data.type = 'group';
					data.disableDrag = true;
				} else {
					data.groupType = 'folder';
					data.type = 'group';
					data.icon += 'tempo-ui-icon-tree-dir-close';
					data.disableDrag = true;
				}
				if(data.children && data.children.length) {
					this._dataProcess(data.children);
				}
			}
			return data;
		},
		_initMenu: function() {
			var $this = this;
			if($.isArray($this.options.menus) && $this.options.menus.length) {
				$this.menu = true;
				this.contextmenu = $("<ul/>").appendTo($("body"))
				.contextmenu({
					data: $this.options.menus,
					select:function(e,ui){
						var id = ui.select.id;
						var linkEl = ui.linkEl;
						$this._selectClick(id, linkEl);
					}
				});
			} else {
				$this.menu = false;
			}
		},
		_selectClick: function(id, linkEl) {
			var onMenuClick = this.options.onMenuClick;
			var item = linkEl.parents('.tempo-groupmenu-item');
			if(!item.length) item = linkEl.parents('.tempo-groupmenu-title');
			onMenuClick.call(this, id, item.data('data'), linkEl);
		},
		_showTree: function(data, search) {
			var $this = this;
			var tree = this.element.find('.explorer-tree');
			var opts = this.options;
			tree.empty();
			tree.groupmenu({
				data: data,
				leftPadding: 15,
				canDrag: opts.canDrag,
				itemMenu: true,
				isButtonEnable: true,
				groupIdField: 'id',
				dragDisHeader:true,
				isDefaultClosed: opts.isDefaultClosed,
				tooltip: function(nodeData){
					return nodeData.name;
				},
				onClickItem: function(e, ui){
					opts.onItemClick.call($this, e, ui);
				},
				onDblClickItem: function(e, ui){
						
				},
				onCheckGroup: function(e, data) {
					console.log("group");
				},
				onCheckItem: function(e, data) {
					$this._wrapShowMenu($(this), e);
				},
				markIcon:opts.markIcon
			});
			this.tree = tree;
			this._bindLeavesEvent();	
		},
		_wrapShowMenu: function(ele, e) {
			e.stopPropagation();
			e.preventDefault();
			var item = ele.parents('.tempo-groupmenu-item');
			if(!item.length) item = ele.parents('.tempo-groupmenu-title');
			this._showMenu(ele, item.data('data'));
			return false;
		},
		_bindLeavesEvent: function(parent) {
			var $this = this;
			// 展示菜单
			var showMenu = $this._wrapShowMenu;
			// 如果没传递父元素，则进行初始化
			if(!parent || !parent.length) {
				parent = this.element;
				parent.find('.tempo-groupmenu-title[menuid="' + $this.options.otherId + '"]').off('mouseover mouseout');
				parent.find('.tempo-groupmenu-title[menuid="' + $this.options.selfId + '"] .tempo-groupmenu-title-mark')
					.off('click')
					.on({
						'click': function(e) {
							return showMenu.call($this, $(this), e);
						}
					});
				parent.find('div[menuid="' + $this.options.selfId +'" ]').droppable({
						accept:'.tempo-groupmenu-title-text,.tempo-groupmenu-item-text',
						drop:function(e,ui){
							var dragEvent = $this.options.onDragEvent;
							dragEvent.call(this, e,ui);
						}
					});
			}
			parent.find('.tempo-groupmenu-item-text').off('click dblclick').on({
				click: function(e) {
					var ele = $(this);
					var item = ele.parents('.tempo-groupmenu-item');
					var onItemClick = $this.options.onItemClick;
					var data = item.data('data');
					if(data.fileType == 'FOLDER') {
						//
					} else {
						onItemClick.call($this, item.data('data'), ele);
					}
				}
			}) ;
			this._bindEventForFolder(parent);
		},
		_bindEventForFolder: function(parent) {
			var $this = this;
			// 重新绑定菜单项的事件
			parent.find('.tempo-groupmenu-item[groupid=folder]').on({
				'mouseover': function(e) {
					var data = $(this).data('data');
					var beforeHover = $this.options.beforeHover || $.noop;
					var r = beforeHover.call(this, data);
					if(r === false) return;
					if($this.menu && !!data.parentId) {
						$(this).find('.tempo-groupmenu-item-mark').show();
					    $(this).find('.tempo-groupmenu-item-mark').removeClass("tempo-ui-icon-no-mutual");
					}
				},
				'mouseout': function(e) {
					$(this).find('.tempo-groupmenu-item-mark').addClass("tempo-ui-icon-no-mutual");
					$(this).find('.tempo-groupmenu-item-mark').hide();
				},
				'click': function(e) {
					var ele = $(this);
					$this._expandLeaf(ele, ele.data('data'))
				}
			}).droppable({
				accept:'.tempo-groupmenu-title-text,.tempo-groupmenu-item-text',
				drop:function(e,ui){
					var dragEvent = $this.options.onDragEvent;
					dragEvent.call(this, e,ui);
				}
			});
			parent.find('.tempo-groupmenu-item-mark').off('click').on('click', function(e) {
	
				$(".explorer-grounpmenu-item-select").removeClass("explorer-grounpmenu-item-select");
				$(this).parents('.tempo-groupmenu-item').addClass("explorer-grounpmenu-item-select");
				
				return $this._wrapShowMenu($(this), e);
			});
			
			//修改选中菜单样式
			parent.find('.tempo-groupmenu-item[groupid!=folder]').on({
			 'click': function(e) {
					var ele = $(this);
					$(".explorer-grounpmenu-item-select").removeClass("explorer-grounpmenu-item-select");
					ele.addClass("explorer-grounpmenu-item-select");
				},
			 'mouseover': function(e) {
				 if(!$(this).hasClass("explorer-grounpmenu-item-select")){
					 $(this).find('.tempo-groupmenu-item-mark').removeClass("tempo-ui-icon-no-mutual");
				 }
			  },
			  'mouseout': function(e) {
				  $(this).find('.tempo-groupmenu-item-mark').addClass("tempo-ui-icon-no-mutual");
				},
			});
		},
		_showMenu: function(ele, data) {
			var offset = ele[0].getBoundingClientRect();
			var beforeShow = this.options.beforeMenuShow || $.noop;
			var r = beforeShow.call(this, data,ele);
			if(!r) return;
			this.contextmenu.contextmenu('showAll');
			if(r && $.isArray(r)) {
				for(var m in this.options.menus) {
					var menu = this.options.menus[m];
					if(r.indexOf(menu.id) == -1) {
						this.contextmenu.contextmenu('hideItem', menu.id)
					}
				}
			}
			var posLeft = offset.left+15;
			var posTop =  offset.top+15;
			var bodyHeight = $("body").height();
			var contextMenuHeight = this.contextmenu.outerHeight();
			var elTop = offset.top - 5 - contextMenuHeight;
			if (bodyHeight < posTop + contextMenuHeight && elTop > 0){
				posTop = elTop;
			}
			this.contextmenu.contextmenu("show", {
				position:{
					left: posLeft,
					top: posTop
				},
				linkEl: ele
			});
			this.contextmenu.css("width","125px");
		},
		_expandLeaf: function(ele, data) {
			var $this = this;
			var tree = this.element.find('.explorer-tree');
			var group = ele.next();
			var index = group.attr('index');
			var open = ele.hasClass('tempo-groupmenu-item-group-select');
			var children = group.children().length;
			var beforeLoadChildren = this.options.onBeforeLoadChildren;
			if(open && beforeLoadChildren.call(this, data) && !children) {
				var beforeQuery = this.options.onBeforeQuery;
				var afterLoad = this.options.onAfterLoad;
				var param = $.extend({}, this.options.param, {parentId: data.id});
				param = beforeQuery.call($this, param);
				$this._ajax(param || {}, function(d) {
					var data = afterLoad.call($this, d, false);
					data = $this._dataProcess(data);
					if(data.length) {
						tree.groupmenu('addMenu', group, Number(index), data);
					}
					this._bindEventForFolder(group);
				});
			}
		},
		_ajax: function(param, callback) {
			var $this = this;
			var d = param;
			if($this.options.contentType.indexOf('application/json') > -1) {
				d = JSON.stringify(param);
			}
			$.ajax({
				url: $this.options.url,
				type: $this.options.method,
				data: d,
				contentType: $this.options.contentType,
				complete: function() {
					
				},
				error: function() {
					callback.call($this, {});
				},
				success: function(data) {
					callback.call($this, data);
				}
			});
		},
		addTreeMenuItem: function(ele, data, addToPrev) {
			var parent = ele.parent().parent().next();
			var index = parent.attr('index') || 1;
			this._dataProcess(data);
			//同级目录增加节点
			if(ele.parent().parent().attr("groupid")!="folder" && ele.parent().parent().attr("menuid") != "sort"){
				this.tree.groupmenu('addMenuItem', parent, Number(index), data,addToPrev);
			}else{
				//子目录下增加节点
				this.tree.groupmenu('addMenuItem', parent, Number(index) + 1, data,addToPrev);
			}
			this._bindEventForFolder(parent);
		},
		//删除节点
		delTreeMenuItem : function(ele) {
			var node = null;
			if(!ele.hasClass("tempo-groupmenu-item")){
				node = ele.closest(".tempo-groupmenu-item");
			}else{
				node = ele;
			}
			node.next().remove();
			node.remove();
		},
		//根据id检索树，若已加载，则返回节点位置
		getMenuById : function(id){
			return this.tree.find("div[menuid='"+id+"']");
		},
		//ele为tempo-groupmenu-item 局部指定url的加载 
		partLoading : function(url,ele,param){
			var $this = this;
			var tree = this.element.find('.explorer-tree');
			var group = ele.next();
			group.hide().html("");
			var index = group.attr('index');
			var $this = this;
			
			if(ele.hasClass("tempo-groupmenu-item-group-select")){
				ele.removeClass("tempo-groupmenu-item-group-select");
			}
			$.ajax({
				url: url,
				type: "POST",
				contentType:"application/json",
				data: JSON.stringify(param || {}),
				complete: function() {
					
				},
				success: function(rs) {
					if(rs.success){
						var tag = false;
						if(!group.hasClass("tempo-groupmenu-content-group")){
							group.addClass("tempo-groupmenu-content-group");
							tag = true;
						}
						var data = $this._dataProcess(rs.data);
						if(!index){
							index = 1;
						}
						tree.groupmenu('addMenu', group, Number(index), data);
						if(tag){
							group.removeClass("tempo-groupmenu-content-group");
						}
						$this._bindEventForFolder(group);
					}
				}
			});
		},
		_destroy: function(){
			
		}
	});
	
})(jQuery);